﻿using Corina.Commands;
using Corina.Common;
using Corina.Datamodel.DataObject;
using Corina.Datamodel.Entities;
using Corina.Enumerations;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Ink;
using System.Windows.Input;

namespace Corina.Cydee.Apphub.Viewmodels
{
    public class CityViewmodel : ViewmodelBase
    {
        public CityViewmodel()
        {
            AreaClient.GetCityItemsCompleted += GetCityItemsCompleted;
            AreaClient.GetProvinceItemsCompleted += GetProvinceItemsCompleted;
            AreaClient.GetNewCityCompleted += GetNewCityCompleted;
            AreaClient.InsertCityCompleted += InsertCityCompleted;
            AreaClient.UpdateCityCompleted += UpdateCityCompleted;
            AreaClient.RemoveCityCompleted += RemoveCityCompleted;
            AreaClient.GetCityInfoCompleted += GetCityInfoCompleted;
            if(DataContext.IsValid)
            {
                LoadData();
                LoadRelatedData();
            }
        }

        private void GetCityInfoCompleted(object sender, DataService.GetCityInfoCompletedEventArgs e)
        {
            if(e.Error== null)
            {
                Operation = EntityOperation.Update;
                UpdateEntity = e.Result.Entities.OfType<CityInfo>().FirstOrDefault();
                SelectedUpdateProvince = ProvinceCollection.FirstOrDefault(t => t.Code == UpdateEntity.Code.Substring(0, 2));
            }
        }

        private void GetProvinceItemsCompleted(object sender, DataService.GetProvinceItemsCompletedEventArgs e)
        {
            if(e.Error == null)
            {
                ProvinceCollection = new ObservableCollection<ProvinceInfo>(e.Result.Entities.OfType<ProvinceInfo>());
            }
        }

        private void RemoveCityCompleted(object sender, DataService.RemoveCityCompletedEventArgs e)
        {
            LoadData();
        }

        private void UpdateCityCompleted(object sender, DataService.UpdateCityCompletedEventArgs e)
        {
            UpdateEntity = new CityInfo();
            Operation = EntityOperation.None;
            LoadData();
        }

        private void InsertCityCompleted(object sender, DataService.InsertCityCompletedEventArgs e)
        {
            SelectedUpdateProvince = null;
            UpdateEntity = new CityInfo();
            Operation = EntityOperation.None;
            
            LoadData();
        }

        private void GetNewCityCompleted(object sender, DataService.GetNewCityCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                UpdateEntity = e.Result.Entities.OfType<CityInfo>().FirstOrDefault();
                Operation = EntityOperation.Insert;
            }
        }

        private void GetCityItemsCompleted(object sender, DataService.GetCityItemsCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                var items = (from t in e.Result.DataObjects
                             select new
                             {
                                 Id = t["Id"],
                                 Code = (string)t["Code"],
                                 Name = (string)t["Name"],
                                 English = (string)t["English"],
                                 PostCode = t["PostCode"],
                                 AreaCode = t["AreaCode"],
                                 Province = t["Province"]
                             });
                CitiesCollection = new ObservableCollection<object>(items);
                ItemsCount = e.Result.TotalCount;
            }

            IsBusy = false;
        }

        protected override void LoadData(params object[] paras)
        {
            IsBusy = true;
            AreaClient.GetCityItemsAsync(SelectedProvince == null ? "" : SelectedProvince.Code, Keywords, Index, 20);
        }

        private void LoadRelatedData()
        {
            AreaClient.GetProvinceItemsAsync("");
        }

        #region Collection
        private ObservableCollection<object> _citiesCollection;
        public ObservableCollection<object> CitiesCollection
        {
            get { return _citiesCollection; }
            set
            {
                _citiesCollection = value;
                RaisePropertyChanged(() => CitiesCollection);
            }
        }

        private ObservableCollection<ProvinceInfo> _provinceCollection;
        public ObservableCollection<ProvinceInfo> ProvinceCollection
        {
            get { return _provinceCollection; }
            set
            {
                _provinceCollection = value;
                RaisePropertyChanged(() => ProvinceCollection);
            }
        }
        #endregion

        #region Update
        private ProvinceInfo _selectedUpdateProvince;
        public ProvinceInfo SelectedUpdateProvince
        {
            get { return _selectedUpdateProvince; }
            set
            {
                _selectedUpdateProvince = value;
                RaisePropertyChanged(() => SelectedUpdateProvince);
                if (SelectedUpdateProvince != null)
                {
                    if (Operation == EntityOperation.Insert)
                    {
                        AreaClient.GetNewCityAsync(Account, Password, SelectedUpdateProvince.Code);
                    }
                }
                else
                {
                    UpdateEntity = new CityInfo();
                }
            }
        }

        private ProvinceInfo _selectedProvince;
        public ProvinceInfo SelectedProvince
        {
            get { return _selectedProvince; }
            set
            {
                _selectedProvince = value;
                RaisePropertyChanged(() => SelectedProvince);
            }
        }

        private CityInfo _updateEntity = new CityInfo();
        public CityInfo UpdateEntity
        {
            get { return _updateEntity; }
            set
            {
                _updateEntity = value;
                RaisePropertyChanged(() => UpdateEntity);
            }
        }
        #endregion

        #region Properties
        private string _keywords = string.Empty;
        public string Keywords
        {
            get { return _keywords; }
            set
            {
                _keywords = value;
                RaisePropertyChanged(() => Keywords);
            }
        }
        #endregion

        #region Commands
        public ICommand LoadCommand
        {
            get {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        Index = 1;
                        LoadData();
                    }
                };
            }
        }

        public ICommand InsertCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        Operation = EntityOperation.Insert;
                    }
                };
            }
        }

        public ICommand EditCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);
                    AreaClient.GetCityInfoAsync(Account, Password, id);
                });
            }
        }

        public ICommand RemoveCommand
        {
            get
            {
                return new DelegateCommand(t =>
                {
                    int id = Convert.ToInt32(t);
                    if(ShowConfirm(Language.LanguageKeys.IDS_DELETE_CONFIRM) == MessageBoxResult.OK)
                    {
                        AreaClient.RemoveCityAsync(Account, Password, id);
                    }
                });
            }
        }

        public ICommand SubmitCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        if(Operation == EntityOperation.Insert)
                        {
                            AreaClient.InsertCityAsync(Account, Password, UpdateEntity.Name, UpdateEntity.English, UpdateEntity.PostCode, UpdateEntity.AreaCode, UpdateEntity.Code);
                        }
                    }
                };
            }
        }

        public ICommand CancelCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        UpdateEntity = new CityInfo();
                        Operation = EntityOperation.None;
                    }
                };
            }
        }
        #endregion

    }
}
